#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#define FILE_NAME "fifo"
#define LOG_PATH "/home/land/109/rev-autumn/rev-sys/log.txt"


bool MAKE_FIFO()
{
    int ret=mkfifo(FILE_NAME,0666);
    if(ret<0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        return false;
    }
    std::cout<<"make fifo success"<<std::endl;
    return true;
}

int main()
{
Start:
    int rfd=open(FILE_NAME,O_RDONLY);
    if(rfd<0)
    {
        std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
        if (MAKE_FIFO()) goto Start;
        else return -1;   
    }
    std::cout << "open fifo success..." << std::endl;


    char buffer[1024];
    while(true)
    {
        memset(buffer,0,sizeof(buffer));
        int ret=read(rfd,buffer,sizeof(buffer));
        if(ret>0)
        {
            int ret2=open(LOG_PATH,O_WRONLY|O_CREAT|O_APPEND,0666);
            if(ret2<0)
            {
                std::cerr << "errno: " << errno << ", errstring: " << strerror(errno) << std::endl;
                return -1;
            }
            buffer[ret]=0;
            write(ret2,buffer,ret);
            close(ret2);
        }
        else if(ret==0)
        {
            std::cout<<"client exit"<<std::endl;
            break;
        }

    }

    return 0;
}

